package cn.tedu.charging.order.config;


import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 连接EMQX 消息中间件的配置类
 * 连接EMQX 的目的是为了和设备通信
 */

@Configuration
public class MqttConfiguration {

    @Autowired
    private MqttContext mqttContext;


    private static final Logger log = LoggerFactory.getLogger(MqttConfiguration.class);
    private String host = "tcp://localhost:1883";

    private String username = "admin";

    private String password = "public";

    private String clientId = "order_service_client" + Math.random();


    @Bean
    public MqttClient mqttClient() throws MqttException {
        //通过客户端ID和连接地址创建MqttClient对象
        MqttClient mqttClient = new MqttClient(host, clientId);
        //创建MqttConnectOptions对象，设置连接选项
        MqttConnectOptions options = new MqttConnectOptions();
        //设置用户名
        options.setUserName(username);
        //设置密码 char[] 字符串转换为字符数组
        options.setPassword(password.toCharArray());

        options.setAutomaticReconnect(true);

        //设置回调函数
        MqttConsumer mqttConsumer = new MqttConsumer(mqttClient, mqttContext);
        mqttClient.setCallback(mqttConsumer);

        //通过配置和EMQX建立连接
        mqttClient.connect(options);

        log.debug("MQTT客户端准备和EMQX连接，是否连接成功不知道" +
                "连接成功的结果是通过Callback回调" +
                "来通知订单服务中的MqttConsumer");
        //返回MqttClient对象
        return mqttClient;
    }
}
